import React, { useState, useRef, useEffect } from 'react';
import './AiChat.css';

interface Message {
  id: string;
  type: 'user' | 'ai';
  content: string;
  timestamp: Date;
}

interface AiChatProps {
  onClose: () => void;
}

const AiChat: React.FC<AiChatProps> = ({ onClose }) => {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      type: 'ai',
      content: '你好！我是AI智能助手，有什么可以帮助你的吗？',
      timestamp: new Date()
    }
  ]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isTyping, setIsTyping] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 打字机效果
  const typeWriter = (text: string, messageId: string, onComplete?: () => void) => {
    setIsTyping(true);
    let index = 0;
    const interval = setInterval(() => {
      if (index < text.length) {
        setMessages(prev => prev.map(msg => 
          msg.id === messageId 
            ? { ...msg, content: text.substring(0, index + 1) }
            : msg
        ));
        index++;
      } else {
        clearInterval(interval);
        setIsTyping(false);
        onComplete?.();
      }
    }, 50); // 50ms间隔，稍微慢一点避免太快
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim() || isLoading) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      type: 'user',
      content: inputValue.trim(),
      timestamp: new Date()
    };

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsLoading(true);

    const aiMessageId = (Date.now() + 1).toString();

    // 添加AI消息占位符
    setMessages(prev => [...prev, {
      id: aiMessageId,
      type: 'ai',
      content: '',
      timestamp: new Date()
    }]);

    try {
      const appCode = localStorage.getItem('AI_APPCODE');
      if (!appCode) throw new Error('未配置AI APPCODE');
      // ==== 真实阿里云请求 ONLY ====
      const resp = await fetch('https://sfdsr1.market.alicloudapi.com/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `APPCODE ${appCode}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: 'gpt-3.5-turbo',
          messages: [
            { role: 'system', content: '你是学生管理系统的AI助手，请用简洁中文回答。' },
            { role: 'user', content: userMessage.content }
          ],
          temperature: 0.7,
          max_tokens: 512,
          stream: false
        })
      });
      if (!resp.ok) {
        let detail = resp.statusText;
        try {
          const errJson = await resp.json();
          detail = errJson?.error?.message || JSON.stringify(errJson);
        } catch {}
        throw new Error(`AI接口调用失败: ${detail}`);
      }
      const data = await resp.json();
      const answer = data?.choices?.[0]?.message?.content || '抱歉，我没有获取到有效的回复。';
      typeWriter(answer, aiMessageId, () => setIsLoading(false));
    } catch (error) {
      console.error('发送消息失败:', error);
      setMessages(prev => prev.map(msg =>
        msg.id === aiMessageId
          ? { ...msg, content: '抱歉，我暂时无法回答你的问题。请稍后再试。' }
          : msg
      ));
      setIsLoading(false);
    }
  };

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // 清空对话
  const clearChat = () => {
    setMessages([{
      id: '1',
      type: 'ai',
      content: '你好！我是AI智能助手，有什么可以帮助你的吗？',
      timestamp: new Date()
    }]);
  };

  return (
    <div className="ai-chat-container">
      <div className="ai-chat-header">
        <h3>AI 智能助手</h3>
        <div className="ai-chat-actions">
          <button onClick={clearChat} className="clear-btn">清空</button>
          <button onClick={onClose} className="close-btn">×</button>
        </div>
      </div>

      <div className="ai-chat-messages">
        {messages.map((message) => (
          <div key={message.id} className={`message ${message.type}`}>
            <div className="message-avatar">
              {message.type === 'user' ? '👤' : '🤖'}
            </div>
            <div className="message-content">
              <div className="message-text">
                {message.content}
                {message.type === 'ai' && message.id === messages[messages.length - 1]?.id && isTyping && (
                  <span className="typing-cursor">|</span>
                )}
              </div>
              <div className="message-time">
                {message.timestamp.toLocaleTimeString()}
              </div>
            </div>
          </div>
        ))}
        {isLoading && (
          <div className="message ai">
            <div className="message-avatar">🤖</div>
            <div className="message-content">
              <div className="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="ai-chat-input">
        <textarea
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="输入你的问题..."
          disabled={isLoading}
          rows={3}
        />
        <button 
          onClick={sendMessage} 
          disabled={!inputValue.trim() || isLoading}
          className="send-btn"
        >
          {isLoading ? '发送中...' : '发送'}
        </button>
      </div>
    </div>
  );
};

export default AiChat;
